package com.weixing.mall.push;

import jodd.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 个推模块
 *
 * @author  siashan
 * @date  2021/1/22 9:45
 * @since  1.0
 **/
@Component("gtComponent")
public class GtComponent {


    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    /**
     * 获取代理端token
     *
     * @return 代理端token
     */
    public  String getDlToken() {
        String token = stringRedisTemplate.opsForValue().get(GtConst.REDIS_DTOKEN_PRE);
        if (StringUtil.isEmpty(token)){
            token = GtUtil.getDlToken();

            stringRedisTemplate.opsForValue().set(GtConst.REDIS_DTOKEN_PRE,token,23, TimeUnit.HOURS);
        }
        return token;
    }


    /**
     * 绑定别名
     *
     * @param aliasList 别名列表
     */
    public  void bindAlias(List<CidAlias> aliasList) {
        GtUtil.bindAlias(aliasList,getDlToken(),GtConst.BIND_ALIAS_URL);
    }


    /**
     * 全推
     *
     * @param pushMsg 推送消息
     */
    public  void pushAll(PushMsg pushMsg) {
        GtUtil.pushAll(pushMsg,getDlToken(),GtConst.PUSH_ALL_URL);
    }

    /**
     * 向单个用户推送消息，可根据cid指定用户
     *
     * @param pushMsg 推送消息
     * @param cid cid
     */
    public  void pushToSingleCid(PushMsg pushMsg,String cid) {
        GtUtil.pushToSingleCid(pushMsg,cid,getDlToken(),GtConst.PUSH_TOSINGLECID_URL);
    }

    /**
     * 创建消息
     *
     * @param pushMsg 推送消息
     */
    public String   listMessage(PushMsg pushMsg) {
        return GtUtil.listMessage(pushMsg,getDlToken(),GtConst.PUSH_LISTMESSAGE_URL);
    }


    /**
     * 批量发送消息给cid
     *
     * @param pushMsg
     */
    public void    listCid(PushMsg pushMsg, List<String> cids) {
        int listSize = cids.size();
        int toIndex = 200;
        for (int i = 0; i < listSize; i += 200) {
            if (i + 200 > listSize) {
                toIndex = listSize - i;
            }
            List newList = cids.subList(i, i + toIndex);
            GtUtil.listCid(newList, listMessage(pushMsg), getDlToken(), GtConst.PUSH_LISTCID_URL);
        }
    }


}
